package com.ljh.onlinetest.controller.admin;

import com.github.pagehelper.PageInfo;
import com.ljh.onlinetest.base.BaseApiController;
import com.ljh.onlinetest.base.RestResponse;
import com.ljh.onlinetest.base.SystemCode;
import com.ljh.onlinetest.domain.Question;
import com.ljh.onlinetest.domain.TextContent;
import com.ljh.onlinetest.domain.enums.QuestionTypeEnum;
import com.ljh.onlinetest.domain.question.QuestionObject;
import com.ljh.onlinetest.service.QuestionService;
import com.ljh.onlinetest.service.TextContentService;
import com.ljh.onlinetest.utils.*;
import com.ljh.onlinetest.viewmodel.admin.question.QuestionEditRequestVM;
import com.ljh.onlinetest.viewmodel.admin.question.QuestionRequestPageVM;
import com.ljh.onlinetest.viewmodel.admin.question.QuestionResponseVM;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author ljh
 * @ClassName QuestionController.java
 * @createTime 2022年01月19日
 */
@RestController("AdminQuestionController")
@RequestMapping("/api/admin/question")
public class QuestionController extends BaseApiController {

    @Autowired
    private QuestionService questionService;
    @Autowired
    private TextContentService textContentService;

    @RequestMapping("/page")
    public RestResponse<PageInfo<QuestionResponseVM>> page(@RequestBody QuestionRequestPageVM requestPageVM){
        PageInfo<Question> pageInfo = questionService.listPage(requestPageVM);
        PageInfo<QuestionResponseVM> vmPageInfo = PageInfoHelper.copyMap(pageInfo, question -> {
            QuestionResponseVM questionResponseVM = modelMapper.map(question, QuestionResponseVM.class);
            questionResponseVM.setCreateTime(DateTimeUtil.dateFormat(question.getCreateTime()));
            questionResponseVM.setScore(ExamUtil.scoreToVM(question.getScore()));
            TextContent textContent = textContentService.selectById(question.getInfoTextContentId());
            QuestionObject questionObject = JsonUtil.toJsonObject(textContent.getContent(),QuestionObject.class);
            String clearHtml = HtmlUtil.clear(questionObject.getTitleContent());//去除html部分显示题目
            questionResponseVM.setShortTitle(clearHtml);
            return questionResponseVM;
        });
        return  RestResponse.ok(vmPageInfo);
    }

    @RequestMapping("/select/{id}")
    public RestResponse<QuestionEditRequestVM> getQuestionById(@PathVariable Integer id){
        QuestionEditRequestVM questionEditRequestVM = questionService.getQuestionEditRequestVM(id);
        return RestResponse.ok(questionEditRequestVM);
    }

    @RequestMapping(value = "/delete/{id}",method = RequestMethod.POST)
    public RestResponse delete(@PathVariable Integer id){
        Question question = questionService.selectById(id);
        question.setDeleted(true);
        questionService.updateByIdFilter(question);
        return RestResponse.ok();
    }


    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public RestResponse editQuestion(@RequestBody @Valid QuestionEditRequestVM model){
        //1.调用验证方法 validQuestionEditRequestVM :RestResponse，验证编辑或者新建的题目是否符合规范
        RestResponse restResponse = validQuestionEditRequestVM(model);
        //2.不规范直接返回验证方法的返回值RestResponse
        if (restResponse.getCode() != SystemCode.OK.getCode()){
            return restResponse;
        }
        //3.符合规范，判断model的id是否为空，为空表示添加新题目，不为空表示修改新题目
        if (null == model.getId()){
            questionService.insertFullQuestion(model,getCurrentUser().getId());
        }else {
            questionService.updateFullQuestion(model);
        }
        return RestResponse.ok();
    }

    private RestResponse validQuestionEditRequestVM(QuestionEditRequestVM model){
        Integer questionType = model.getQuestionType();
        boolean requireCorrect = questionType == QuestionTypeEnum.SingleChoice.getCode() || questionType == QuestionTypeEnum.TrueFalse.getCode();
        if (requireCorrect) {
            if (StringUtils.isBlank(model.getCorrect())){
                String errorFormat = ErrorUtil.parameterErrorFormat("correct", "不能为空");
                return new RestResponse(SystemCode.ParameterValidError.getCode(), errorFormat);
            }
        }

        if (questionType == QuestionTypeEnum.GapFilling.getCode()){
            model.setCorrect(model.getItems().get(0).getContent());
            Integer fillSumScore = model.getItems().stream().mapToInt(d -> ExamUtil.scoreFromVM(d.getScore())).sum();
            Integer questionScore = ExamUtil.scoreFromVM(model.getScore());
            if (!fillSumScore.equals(questionScore) ){
                String errorMsg = ErrorUtil.parameterErrorFormat("score","空分数和题目总分不相等");
                return new RestResponse(SystemCode.ParameterValidError.getCode(), errorMsg);
            }
        }
       return RestResponse.ok();

    }
}
